import os.path

from flask import Flask
from flask_login import LoginManager

# 导入models.py模块中的db对象
from .models import db

# 需要创建一个login_manager对象
login_manager=LoginManager()

# 该函数主要用于进行蓝图的注册
def create_app():
    # 明确了templates目录的位置，防止找不到html模板
    # Flask(__name__,template_folder='../templates',static_folder='../static')

    # join方法，可以__file__与templates进行字符串拼接，
    app=Flask(__name__,template_folder=os.path.join(os.path.dirname(__file__),'../templates'),
              static_folder=os.path.join(os.path.dirname(__file__),'../static'))

    # 明确加载配置文件
    app.config.from_pyfile('../config.py')

    # 把当前项目app对象，注册到db对象中。把app对象和db对象整合在一起！
    db.init_app(app)

    # 把login_manager与当前app绑定
    login_manager.init_app(app)

    # 导入蓝图--->使用范围仅限于当前函数
    from app.routes.index import bp as index_bp
    from app.routes.auth import bp as auth_bp
    from app.routes.goods import bp as goods_bp
    from app.routes.user_center import bp as user_bp
    from app.routes.admin import bp as admin_bp
    from app.routes.profile import bp as profile_bp
    from app.routes.notification import bp as notification_bp

    # 注册蓝图
    app.register_blueprint(index_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(goods_bp)
    app.register_blueprint(user_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(profile_bp)
    app.register_blueprint(notification_bp)

    return app;

# 加载当前用户----》查询users表中对应的用户
@login_manager.user_loader
def load_user(user_id):
    from app.models import User
    # select * from users where id=?
    return User.query.get(int(user_id))